/*
 * @Author: zhangsheng zhangsheng@zhixueyun.com
 * @Date: 2024-11-12 20:54:36
 * @LastEditors: zhangsheng zhangsheng@zhixueyun.com
 * @LastEditTime: 2024-11-12 23:36:41
 * @FilePath: \react-demo\src\views\myhooks\UseMemoHook.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React, { useMemo, useState } from "react";

function filterUsers(users, searchTerm) {
    return users.filter((user) => user.name.includes(searchTerm));
}

function useMemoDemo() {
    const [searchTerm, setSearchTerm] = useState("");
    const [isDark, setIsDark] = useState(false);

    const allUsers = useMemo(() => {
        let list = [];
        for (let i = 1; i <= 500; i++) {
            list.push({ id: i, name: `User${i}` });
        }
        return list;
    }, []);

    const useMemoCurrentUsers = useMemo(() => {
        console.log('with useMemo')
        return filterUsers(allUsers, searchTerm);
    }, [allUsers, searchTerm]);

    return (
        <div>
            {/* 每一次更改查询框内容，都会触发useMemo */}
            <input
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                placeholder="Search by name..."
            />

            {/* 每一次更改背景色，都不会触发useMemo */}
            <button onClick={() => setIsDark((pre) => !pre)}>
                {isDark ? "Dark mode" : "Light mode"}
            </button>

            <div>
                <div>
                    <h2>With useMemo</h2>
                    <div style={{ background: isDark ? "rgba(0,0,0,0.5)" : ""}}>
                        {useMemoCurrentUsers.map((user) => (
                            <div key={user.id}>
                                {user.name}
                            </div>
                        ))}
                    </div>
                </div>
            </div>
        </div>
    );
}

export default useMemoDemo;